import React, { Component } from "react";
import Slider from "react-slick";
import banner from "../images/banner.jpg";
import axios from "axios";
class IndexBanner extends Component {
  state = { banners: [] };
  componentDidMount() {
    axios.get("/Tgh/data/index_swiper_url").then(res => {
      // console.log(res.data.data);
      this.setState({ banners: res.data.data });
    });
  }
  render() {
    return <div className="banner-Container">{this.renderBanners()}</div>;
  }
  renderBanners() {
    // banner的设置
    var settings = {
      dots: true,
      infinite: true,
      speed: 1000,
      slidesToShow: 1,
      slidesToScroll: 1,
      autoplay: true,
      autoplaySpeed: 3000,
      arrows: false,
      lazyLoad: 3,
      onSwipe: () => {
        this.slider.slickPause();
        this.slider.slickPlay();
      }
    };
    if (this.state.banners.length !== 0) {
      const bannerList = this.state.banners.map(banner => {
        const { id } = banner;
        let imgUrl = banner.img_url || "";
        // console.log(banner);
        if(imgUrl.indexOf("http") === -1){
          imgUrl = `/images/${imgUrl}`
        }
        return (
          <div key={id}>
            <div className="banner">
              <div
                style={{ backgroundImage: `url(${imgUrl})` }}
                className="banner_div"
                title="banner"
              />
            </div>
          </div>
        );
      });
      return (
        <Slider ref={c => (this.slider = c)} {...settings}>
          {bannerList}
        </Slider>
      );
    } else {
      return (
        <Slider ref={c => (this.slider = c)} {...settings}>
          <div>
            <div className="banner">
              <div
                style={{ backgroundImage: `url(${banner})` }}
                className="banner_div"
                title="banner"
              />
            </div>
          </div>
          <div>
            <div className="banner">
              <div
                style={{ backgroundImage: `url(${banner})` }}
                className="banner_div"
                title="banner"
              />
            </div>
          </div>
        </Slider>
      );
    }
  }
}
export default IndexBanner;
